var gulp = require('gulp');
var pug = require('gulp-pug');
var less = require('gulp-less');
var cleanCSS = require('gulp-clean-css');
var livereload = require('gulp-livereload');
var webserver = require('gulp-webserver');
var del = require('del');
var autoprefixer = require('gulp-autoprefixer');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var lib = require('./src/lib/lib.js');

var paths = {
    images: 'assets/img/**/*',
    views:  'src/views/**/*.pug',
    pages: 'src/views/pages/**/*.pug',
    styles: 'src/less/**/*.less',
    scripts: ['src/**/*.js'],
    libs: './src/lib/*.js'
  };

gulp.task('clean', function() {
    return del(['dist/*']);
});

gulp.task('views', function buildHTML() {
    //convert pug to HTML
    return gulp.src(paths.pages)
    .pipe(plumber())
    .pipe(pug({
        pretty:true
    }))
    .pipe(gulp.dest('dist/views'))
    .pipe(livereload());;
});

gulp.task('less', function () {
  return gulp.src(['./src/less/style.less'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(autoprefixer({
        browsers: ['cover 99.5%'],
        cascade: false
    }))
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist/css'))
    .pipe(livereload());
});

gulp.task('vendor', function() {
  return gulp.src(lib)
    .pipe(plumber())
    .pipe(concat('vendor.js'))
    .pipe(gulp.dest('./dist/js'))
    .pipe(livereload());
});

gulp.task('scripts', function() {
  return gulp.src('./src/js/**/*.js')
    .pipe(plumber())
    .pipe(buffer())
    .pipe(concat('bundle.js'))
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist/js'))
    .pipe(livereload());
});

// Webserver default host 8000
gulp.task('webserver', function() {
    gulp.src('./')
      .pipe(webserver({
        livereload: true,
        directoryListing: true
      }));
  });

// Rerun the task when a file changes
gulp.task('watch', function() {
    livereload.listen({ start: true });
    gulp.watch(paths.views, ['views']);
    gulp.watch(paths.styles, ['less']);
    gulp.watch(paths.libs, ['vendor']);
    gulp.watch(paths.scripts, ['scripts']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch','views','less','vendor','scripts','webserver']);